import path from "node:path";
import {fileURLToPath} from "node:url";
import {execSync} from "node:child_process";
import fs from "node:fs";

const base = path.dirname(fileURLToPath(import.meta.url));
const __dirname = path.resolve(base, 'hope-form/scripts')
const dir = path.resolve(__dirname, "../packages");
fs.readdirSync(dir)
    .map((v) => [path.join(dir, v), path.join(dir, v, "package.json")])
    .filter(([_, p]) => fs.existsSync(p))
    .map(([_, p]) => [_, p, JSON.parse(fs.readFileSync(p, "utf-8"))])
    .filter(([_b, _p, pkg]) => pkg.private !== "true" && pkg.private !== true)
    .forEach(([b, p, pkg]) => {
        const nextVersion = pkg.version.replace(
            /(alpha\.)(\d+)$/,
            (_, p, v) => p + (Number(v) + 1),
        );
        pkg.version = nextVersion;
        fs.writeFileSync(p, JSON.stringify(pkg, null, 2));
        const readmeFile = path.resolve(b, "README.MD");
        fs.writeFileSync(
            path.resolve(b, readmeFile),
            fs
                .readFileSync(readmeFile, "utf-8")
                .replace(/(npm&message=)([^&]+)&/, `$1${nextVersion}&`),
        );
    });

const root = path.resolve(__dirname, "../");
execSync("git add .", {cwd: root});
execSync('git commit -m "build: update to next version"', {cwd: root});
const branch = execSync('git status', {cwd: root}).toString('utf-8').match(/On branch (.+)\s*/)?.[1];
if (!branch) {
    console.error('获取当前分支失败')
    process.exit(1);
}
console.info(`publish branch: ${branch}`)
// --registry
execSync(`pnpm compile && pnpm publish -r --publish-branch=${branch}`, {cwd: root, stdio: 'inherit'})
